package com.usian.admin.gateway.filter;

import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

@Component//包扫描
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1判断当前是否登录请求，如果是就放行
        if (request.getURI().getPath().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }
        //2.获取当前用户的请求头
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //3.判断当前令牌是否存在
        if (StringUtils.isEmpty(token)) {
            //如果不存在，向客户端返回错误信息提示
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        //4.如果令牌存在，然后对jwt令牌进行解析，判断令牌是否合法，如果不合法，则向客户端返回错误信息
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claims);
        if (i == -1 || i == 0) { //-1有效 ，0 有效，快到期了
            //5.如果合法，则向header中重新设置use
            Integer id = (Integer) claims.get("id");
            ServerHttpRequest newRequest= request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId", String.valueOf(id));
                }
            }).build();
            exchange.mutate().request(newRequest).build();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
